package com.tcoiss.webservice.apiServer;


import com.tcoiss.webservice.domain.K3FormVo;
import com.tcoiss.webservice.domain.K3LoginVo;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class K3CloudServer {
    // K3 Cloud WebSite URL Example "http://192.168.19.113/K3Cloud/"
    public static String POST_K3CloudURL = "http://192.168.0.66/k3cloud/";
    //public static String POST_K3CloudURL = "http://111.75.201.86:9775/k3cloud/";
    // Cookie 值
    private static String CookieVal = null;
    private static Map<String, String> map = new HashMap<String, String>();

    static {
        map.put("Save",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");
        map.put("View",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc");
        map.put("Submit",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
        map.put("Audit",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");
        map.put("UnAudit",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc");
        map.put("StatusConvert",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.StatusConvert.common.kdsvc");
        map.put("Delete",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete.common.kdsvc");
        map.put("Login","Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc");
    }

    // HttpURLConnection
    private static HttpURLConnection initUrlConn(String httpUrl,String url, JSONArray paras)
            throws Exception {
        URL postUrl = new URL(httpUrl.concat(url));
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        if (CookieVal != null) {
            connection.setRequestProperty("Cookie", CookieVal);
        }
        if (!connection.getDoOutput()) {
            connection.setDoOutput(true);
        }
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json");
        DataOutputStream out = new DataOutputStream(
                connection.getOutputStream());
        UUID uuid = UUID.randomUUID();
        int hashCode = uuid.toString().hashCode();
        JSONObject jObj = new JSONObject();
        jObj.put("format", 1);
        jObj.put("useragent", "ApiClient");
        jObj.put("rid", hashCode);
        jObj.put("parameters", chinaToUnicode(paras.toString()));
        jObj.put("timestamp", new Date().toString());
        jObj.put("v", "1.0");
        out.writeBytes(jObj.toString());
        out.flush();
        out.close();
        return connection;
    }

    // Login
    public static String login(String httpUrl, K3LoginVo loginVo)
            throws Exception {
        boolean bResult = false;
        String sUrl = map.get("Login").toString();
        JSONArray jParas = new JSONArray();
        jParas.put(loginVo.getDbId());// 帐套Id
        jParas.put(loginVo.getUser());// 用户名
        jParas.put(loginVo.getPwd());// 密码
        jParas.put(2052);// 语言
        HttpURLConnection connection = initUrlConn(httpUrl,sUrl, jParas);
        // 获取Cookie
        String key = null;
        for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
            if (key.equalsIgnoreCase("Set-Cookie")) {
                String tempCookieVal = connection.getHeaderField(i);
                if (tempCookieVal.startsWith("kdservice-sessionid")) {
                    CookieVal = tempCookieVal;
                    break;
                }
            }
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        /*while ((line = reader.readLine()) != null) {
            String sResult = new String(line.getBytes(), "utf-8");
            System.out.println(sResult);
            bResult = line.contains("\"LoginResultType\":1");
            //bResult = line.contains("");
        }*/
        String sResult = "";
        while ((line = reader.readLine()) != null) {
            sResult = new String(line.getBytes(), "utf-8");
        }
        reader.close();
        connection.disconnect();
        return sResult;
    }


    public static String operation(String httpUrl, String requestType, K3FormVo formVo) throws Exception {
        return Invoke(httpUrl,requestType, formVo);

    }
    private static String Invoke(String httpUrl,String requestType,K3FormVo formVo)
            throws Exception {
        String sUrl = map.get(requestType).toString();
        JSONArray jParas = new JSONArray();
        jParas.put(formVo.getFormId());
        jParas.put(formVo.getContent());
        HttpURLConnection connectionInvoke = initUrlConn(httpUrl,sUrl, jParas);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connectionInvoke.getInputStream()));
        String line;

        String sResult = "";
        while ((line = reader.readLine()) != null) {
            sResult = new String(line.getBytes(), "utf-8");
        }
        reader.close();
        connectionInvoke.disconnect();
        return sResult;
    }

    /**
     * 把中文转成Unicode码
     *
     * @param str
     * @return
     */
    public static String chinaToUnicode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            int chr1 = (char) str.charAt(i);
            if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
                result += "\\u" + Integer.toHexString(chr1);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }



}

